package com.example.aics.config;

import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import com.example.aics.store.MongoChatMemotyStore;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import jakarta.annotation.Resource;

@Configuration
public class XiaoZhiChatAssistantConfig {

    @Resource
    private MongoChatMemotyStore mongoChatMemotyStore;

    @Resource
    private EmbeddingStore<TextSegment> embeddingStore;

    @Resource
    private EmbeddingModel embeddingModel;
   

    @Bean
    public ChatMemoryProvider xiaozhiChatMemoryProvider(){
        return memoryId -> MessageWindowChatMemory
                     .builder()
                     .id(String.valueOf(memoryId))
                     .maxMessages(20)
                     // .chatMemoryStore(new InMemoryChatMemoryStore())
                     .chatMemoryStore(mongoChatMemotyStore)
                     .build();
    }


    /**
     * 基于内存向量存储的内容检索器
     * @return
     */
    @Bean
    public ContentRetriever xiaoZhiContentRetrieverInMemory(){

        // 加载文档 ,使用默认的文档解析器，解析文档
        PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.{txt,md}");
        List<Document> documentsList = FileSystemDocumentLoader.loadDocuments("/Volumes/work/AIWorkspace/langchain4j-examples/src/main/documents/rag", pathMatcher);

        // 使用内存向量存储
        InMemoryEmbeddingStore<TextSegment> embeddingStoreInMemory = new InMemoryEmbeddingStore<>();

        if(!CollectionUtils.isEmpty(documentsList)){
            // 使用默认的文档分割器，分割文本，并保存到向量存储中
            EmbeddingStoreIngestor.ingest(documentsList, embeddingStoreInMemory);
        }

        // 从向量存储中创建内容检索器
        return EmbeddingStoreContentRetriever.from(embeddingStoreInMemory);
    }

    /**
     * 基于向量存储(持久化)的内容检索器
     * @return
     */
    @Bean
    public ContentRetriever xiaoZhiContentRetriever(){
        return EmbeddingStoreContentRetriever.builder()
                .embeddingStore(embeddingStore)  // 指定要使用的向量存储
                .embeddingModel(embeddingModel)  // 指定要使用的嵌入模型
                .maxResults(5)  // 最多返回的匹配结果数量
                .minScore(0.5)  // 最小的相似度分数
                .build();
    }

}
